<?php


namespace api\controllers;


use api\components\BaseController;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\helpers\TransformApi;
use common\models\Activity;
use common\models\ActivityEnter;
use common\models\User;
use Yii;

class UserController extends BaseController
{
    /**
     * 获取用户信息
     * @return array
     */
    public function actionInfo()
    {
        $userid = self::$userid;
        $user = User::find()->where(['id'=>$userid])
            ->select(['headimgurl','info','start_time','end_time'])
            ->asArray()
            ->one();
        $huiyuan = (new User())->isHuiyuan($userid,$user['start_time'],$user['end_time'],1);
        $info = json_decode($user['info'],true);
        $end_time = '';
        if ($huiyuan){
            $end_time = date('Y-m-d H:i',strtotime($user['end_time']));
        }
        $data = [
            'headimgurl'=>$user['headimgurl'],
            'nickname'=>$info['nickName']??'',
            'is_huiyuan'=>$huiyuan?1:0,
            'end_time'=>$end_time,
        ];
        return commonApi::message('成功',true,$data);
    }

    /**
     * 我的活动
     * @return array
     */
    public function actionActivity()
    {
        $page = (int)Yii::$app->request->get('page',1);
        $userid = self::$userid;
        $query = ActivityEnter::find()
            ->where(['userid'=>$userid])
            ->orderBy(['create_time'=>SORT_DESC]);
        $data = PageApi::apiPage($query,$page);
        $arr = [];
        $act_ids = array_column($data['data'],'act_id');
        $activity = Activity::find()->where(['id'=>$act_ids])->select(['id','total','surplus'])->asArray()->all();
        $activity = array_column($activity,null,'id');
        foreach ($data['data'] as $datum){
            $info = json_decode($datum['info'],true);
            $registered = $activity[$datum['act_id']]['total']-$activity[$datum['act_id']]['surplus'];
            $arr[] = [
                'main_img' => commonApi::getDomain($info['main_img']),
                'price' => $datum['pay_amount'],
                'name' => $info['name'],
                'start_time' => date('Y-m-d',strtotime($info['start_time'])),
                'end_time' => date('Y-m-d',strtotime($info['end_time'])),
                'act_id' => $datum['act_id'],
                'registered' => $registered,
                'total' => $activity[$datum['act_id']]['total'],
                'surplus' => $activity[$datum['act_id']]['surplus'],
            ];
        }
        $data['data'] = $arr;
        return commonApi::message('成功',true,$data);
    }
}